﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using Mussel;
using Mussel.Data;
using Natrue.Web.MVC;

namespace CostTrade.WebApp.Controllers
{
    [HandleError]
    public class AccountController : AuthController
    {
        private readonly static IDictionary<string, Guid> userAndSessionKeyMapCache = new Dictionary<string, Guid>();

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Login()
        {
            return View();
        }

        [ValidateAntiForgeryToken, AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(string username, string password, string backUrl)
        {
            ClearCookies();

            ISessionManager mgr = ProxyContainer.FindLocalProxy<ISessionManager>();
            AuthenticationInfo authInfo = new AuthenticationInfo { UserName = username, Password = password };

            try
            {
                Passport passport = mgr.Login(authInfo) as Passport;
                if (passport == null) throw new Exception("登录失败");
                Response.Cookies.Add(new HttpCookie("SessionKey", passport.SessionId.ToString()));
                Response.Cookies.Add(new HttpCookie("currentUserId", passport.UserId.ToString()));
                if (userAndSessionKeyMapCache.ContainsKey(passport.UserName))
                    userAndSessionKeyMapCache[passport.UserName] = passport.SessionId;
                else userAndSessionKeyMapCache.Add(passport.UserName, passport.SessionId);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("_FORM", ex.Message);
                return View();
            }

            if (String.IsNullOrEmpty(backUrl))
                return RedirectToAction("Index", "Home");
            return Redirect(backUrl);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Logout()
        {
            ClearCookies();
            return RedirectToAction("Login");
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Exit()
        {
            ClearCookies();
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public bool SayOnline(Guid sessionKey, string userName)
        {
            if (!userAndSessionKeyMapCache.ContainsKey(userName)) return false;
            if (userAndSessionKeyMapCache[userName] != sessionKey) return false;

            ISessionManager mgr = ProxyContainer.FindLocalProxy<ISessionManager>();
            if (mgr.IsOnline(sessionKey))
            {
                mgr.UpdateLinkTime(sessionKey);
                return true;
            }
            return false;
        }

        private void ClearCookies()
        {
            //if(CurrentUser!=null)
            //{
            //    if (userAndSessionKeyMapCache.ContainsKey(CurrentUser.UserName))
            //        userAndSessionKeyMapCache.Remove(CurrentUser.UserName);
            //}

            HttpCookie currUserIdCk = Request.Cookies["currentUserId"];
            if (currUserIdCk != null)
            {
                currUserIdCk.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(currUserIdCk);
            }

            HttpCookie sessionKeyCK = Request.Cookies["SessionKey"];
            if (sessionKeyCK == null) return;

            Guid sessionId = new Guid(sessionKeyCK.Value);
            if (Guid.Empty != sessionId)
            {
                try
                {
                    ISessionManager mgr = ProxyContainer.FindLocalProxy<ISessionManager>();
                    mgr.Logout(sessionId);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            sessionKeyCK.Expires = DateTime.Now.AddDays(-1);
            Response.Cookies.Add(sessionKeyCK);
        }
    }
}
